package com.example.drugaiservice.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.example.drugaiservice.common.result.Result;
import com.example.drugaiservice.common.utils.AuthAccess;
import com.example.drugaiservice.pojo.entity.Drug;
import com.example.drugaiservice.pojo.entity.UrlAndName;
import com.example.drugaiservice.pojo.vo.DrugVO;
import com.example.drugaiservice.service.AskService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {
    private final AskService askService;
    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    //此接口为通过图片上传获取药品名称和药品信息
    //此接口仅用于药品识别
    @PostMapping("/upload")
    public Result<DrugVO> upload(MultipartFile file) throws Exception {
        Drug drug = askService.findPandReturnDrug(file.getBytes());
        String originalFilename = file.getOriginalFilename();
        //aa.png
        String mainName = FileNameUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);//不存在创建
        }
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;//存在命名
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);//存储本地
        String url = "http://localhost:8088/file/download/" + originalFilename;
        return Result.success(DrugVO.builder().
                url(url).
                name(drug.getName()).
                intro(drug.getIntro()).
                build());
    }

    //此接口仅用于病历单识别中图片上传部分
    @PostMapping("/upload2")
    public Result<UrlAndName> upload2(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String mainName = FileNameUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);//不存在创建
        }
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;//存在命名
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);//存储本地
        String url = "http://localhost:8088/file/download/" + originalFilename;
        return Result.success(UrlAndName.builder().name(originalFilename).url(url).build());
    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public Result download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        String filePath = ROOT_PATH + File.separator + fileName;
        System.out.println(filePath);
        if (!FileUtil.exist(filePath)) {
            return Result.error("无法访问");
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        return Result.success();
    }
}
